"use strict";

let EQuickSearch = function () {
    let target;
    let form;
    let input;
    let closeIcon;
    let resultWrapper;
    let resultDropdown;
    let resultDropdownToggle;
    let inputGroup;
    let query = '';

    let hasResult = false;
    let timeout = false;
    let isProcessing = false;
    let requestTimeout = 200; // ajax request fire timeout in milliseconds
    let spinnerClass = 'e-spinner e-spinner--input e-spinner--sm e-spinner--brand e-spinner--right';
    let resultClass = 'e-quick-search--has-result';
    let minLength = 2;
    /**
     * 显示等待状态
     */
    let showProgress = function () {
        isProcessing = true;
        inputGroup.addClass(spinnerClass);

        if (closeIcon) {
            closeIcon.hide();
        }
    };
    /**
     * 隐藏等待状态
     */
    let hideProgress = function () {
        isProcessing = false;
        inputGroup.removeClass(spinnerClass);

        if (closeIcon) {
            if (input.val().length < minLength) {
                closeIcon.hide();
            } else {
                closeIcon.css('display', 'flex');
            }
        }
    };
    /**
     * 显示搜索
     */
    let showDropdown = function () {
        if (resultDropdownToggle && !resultDropdown.hasClass('show')) {
            $(resultDropdownToggle).dropdown('toggle');
            $(resultDropdownToggle).dropdown('update');
        }
    };
    /**
     * 隐藏搜索
     */
    let hideDropdown = function () {
        if (resultDropdownToggle && resultDropdown.hasClass( 'show')) {
            $(resultDropdownToggle).dropdown('toggle');
        }
    };
    /**
     * 执行搜索
     */
    let processSearch = function () {
        // 如果有结果并且查询条件=当前输入条件
        if (hasResult && query === input.value) {
            hideProgress();
            target.addClass(resultClass);
            showDropdown();
            EUtil.scrollUpdate(resultWrapper[0]);
            return;
        }
        // 查询条件
        query = input.val();

        target.removeClass(resultClass);
        showProgress();
        // 这里暂时只对菜单进行搜索
        let result = searchMenu(query);
        resultWrapper.empty();
        if (result.length > 0) {
            hasResult = true;
            // 加载数据到搜索结果中
            $(result).each(function (index, menu) {
                resultWrapper.append(
                    '<a href="' + basePath + menu.url + '" data-title="' + menu.relName + '" class="e-notification-item e-tab-page-link">\
                        <div class="e-notification-item-icon">' + menu.icon + '</div>\
                        <div class="e-notification-item-details">\
                            <div class="e-notification-item-title">' + menu.name + '</div>\
                        </div>\
                    </a>'
                );
            });
        } else {
            hasResult = false;
            resultWrapper.html(
                '<div class="e-grid e-grid--ver" style="min-height: 200px;">\
                    <div class="e-grid e-grid--hor e-grid-item e-grid-item--fluid e-grid-item--middle">\
                        <div class="e-grid-item e-grid-item--middle e-align-center">\
                            暂无数据\
                        </div>\
                    </div>\
                </div>'
            );
        }
        hideProgress();
        target.addClass(resultClass);
        showDropdown();
        EUtil.scrollUpdate(resultWrapper[0]);
    };
    /**
     * 根据关键字搜索菜单
     *
     * @param query {string} 关键字
     * @return {Array} 菜单列表
     */
    let searchMenu = function (query) {
        let result = [];
        if(EUtil.isNotBlank(query)){
            // query = query.toUpperCase();
            let menus = ETool.getUser(true).menus;
            $(menus).each(function (index, menu) {
                if (EUtil.isNotBlank(menu.url) && menu.name.indexOf(query) > -1) {
                    result.push({
                        name: menu.name.replace(new RegExp(query, 'g'), '<span class="e-font-danger">' + query + '</span>'),
                        relName: menu.name,
                        icon: menu.icon,
                        url: menu.url
                    })
                }
            });
        }
        return result;
    };
    /**
     * 取消
     *
     * @param e
     */
    let handleCancel = function (e) {
        input.val('');
        query = '';
        hasResult = false;
        closeIcon.hide();
        target.removeClass(resultClass);
        hideDropdown();
    };

    let handleSearch = function () {
        if (input.val().length < minLength) {
            hideProgress();
            hideDropdown();
            return;
        }

        if (isProcessing === true) {
            return;
        }

        if (timeout) {
            clearTimeout(timeout);
        }

        timeout = setTimeout(function () {
            processSearch();
        }, requestTimeout);
    };

    return {
        init: function ($element) {
            target = $element;
            // Init
            form = $element.find('.e-quick-search-form');
            input = $element.find('.e-quick-search-input');
            closeIcon = $element.find('.e-quick-search-close');
            resultDropdown = $element.find('.dropdown-menu');
            resultDropdownToggle = $element.find('[data-toggle="dropdown"]');
            inputGroup = $element.find('.input-group');
            resultWrapper = $(target).find('.e-quick-search-wrapper');

            input.on('keyup', handleSearch);
            input.on('focus', handleSearch);

            // 按回车
            form.on('keypress', function (e) {
                let key = e.charCode || e.keyCode || 0;
                if (key === 13) {
                    e.preventDefault();
                }
            });

            closeIcon.on('click', handleCancel);

            // 打开搜索将焦点放到input上
            let $toggle = $('#quick_search_toggle');
            if ($toggle.length) {
                $toggle.on('shown.bs.dropdown', function () {
                    input.focus();
                });
            }
        }
    };
};

$(document).ready(function () {
    let $quickSearch = $('#quick_search_inline');
    if ($quickSearch.length) {
        EQuickSearch().init($quickSearch);
    }
});